package com.open.custom.api.controller;

import com.open.custom.api.service.business.OssClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;


@RestController
@Slf4j
@RequestMapping(value = "/file/v1")
public class FileRestController {

    @Autowired
    private OssClient ossClient;

    @PostMapping(value = "/upload")
    public String upload(@RequestParam("file") MultipartFile file) throws Exception {
        try (final InputStream inputStream = file.getInputStream()) {
            return ossClient.save(inputStream.readAllBytes());
        }
    }

    @GetMapping(value = "/download/{fileId}")
    public ResponseEntity<byte[]> download(@PathVariable("fileId") String fileId) throws Exception {
        final byte[] bytes = ossClient.get(fileId);
        return ResponseEntity.ok()
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .header("Content-Disposition", "attachment; filename=" + fileId)
                .body(bytes);
    }

    @PostMapping(value = "/uploadByte")
    public String upload(@RequestBody byte[] bytes) throws Exception {
        return ossClient.save(bytes);
    }

    @GetMapping(value = "/downloadByte/{fileId}")
    public byte[] downloadByte(@PathVariable("fileId") String fileId) throws Exception {
        return ossClient.get(fileId);
    }


}
